﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace DataAccessLayer
{
    /// <summary>
    /// The DAL reader.
    /// Uses to read data from DB
    /// </summary>
    public class Reader
    {
        /// <summary>
        /// The current element.
        /// </summary>

        /// <summary>
        /// The DB - DAL properties mapping.
        /// Item1 - name,
        /// Item2 - dbName,
        /// Item3 - sqlParam,
        /// Item4 - type,
        /// Item5 - size
        /// </summary>
        private List<Tuple<string, string, string, SqlDbType, int>> _properties;

        /// <summary>
        /// Gets the current element.
        /// </summary>
        public Dictionary<string, object> Current { get; internal set; }

        private SqlDataReader reader;
        private SqlConnection connection;


        /// <summary>
        /// Initializes a new instance of the <see cref="Reader"/> class.
        /// </summary>
        /// <exception cref="NotImplementedException">
        /// </exception>
        internal Reader(SqlCommand command, List<Tuple<string, string, string, SqlDbType, int>> properties)
        {
            Current = new Dictionary<string, object>();
            connection = CreateConnection(command);
            connection.Open();
            reader = command.ExecuteReader();
            _properties = properties;
        }

        /// <summary>
        /// Read the next element.
        /// </summary>
        public bool Read()
        {
            if (!reader.Read())
                return false;
            Current = new Dictionary<string, object>();
            for(int i = 0; i < _properties.Count; i++)
                Current[_properties[i].Item1] = reader[_properties[i].Item2];

            return true;
        }

        /// <summary>
        /// Close the reader.
        /// </summary>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public void Close()
        {
            reader.Close();
            connection.Close();
        }


        internal static SqlConnection CreateConnection(SqlCommand command)
        {
            SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog=Tracking; Integrated Security=SSPI;");
            command.Connection = connection;
            command.CommandType = CommandType.StoredProcedure;
            return connection;
        }
    }
}
